package com.blacksea.resourceserver.web.security.token;

import com.blacksea.resourceserver.web.security.feign.FeignService;
import com.blacksea.resourceserver.web.security.request.VerifyOAuth2TokenRequest;
import com.blacksea.resourceserver.web.security.response.VerifyOAuth2TokenResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Token管理, jwt
 *
 * @author blacksea3(jxt) 2021/2/7 12:59
 */
@Component(value = "tokenManager")
public class TokenManager {

    // 过期时间, 单位ms
    // private long tokenExpiration = 24*60*60*1000;

    // @Value("${jwt-token-sign}")
    // private String jwt_token_sign;

    @Autowired
    private FeignService feignService;

    /**
     * 根据token 向远程获得username
     *
     * @param token .
     * @return .
     */
    public String getUserByTokenFromRemote(String token) {
        VerifyOAuth2TokenResponse checkTokenRespVO = feignService.checkToken(new VerifyOAuth2TokenRequest(token));
        boolean checkRet = "SUCCESS".equals(checkTokenRespVO.getState());

        if (checkRet) {
            // Map<String, Object> body = Jwts.parser().setSigningKey(jwt_token_sign).parseClaimsJws(token).getBody();
            // String username = (String) body.get("username");
            return "OKOK";
        } else {
            return null;
        }
    }

    /**
     * 根据token, 从缓存获得用户信息
     * 当前禁用: 不设置缓存
     *
     * @param token .
     * @return .
     */
    public String getUserByTokenFromCache(String token) {
        return "";
    }

    /**
     * 从缓存删除token
     * 当前禁用: 不设置缓存
     *
     * @param token .
     */
    public void removeTokenFromCache(String token) {
    }

    /**
     * 向缓存写入token:username信息
     * 当前禁用: 不设置缓存
     *
     * @param token .
     * @param username .
     */
    public void addTokenToCache(String token, String username) {
    }
}
